package com.ukefu.webim.web.interceptor;

import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;

import com.ukefu.core.UKDataContext;
import com.ukefu.util.Menu;
import com.ukefu.util.UKTools;
import com.ukefu.webim.service.cache.CacheHelper;
import com.ukefu.webim.util.RLogWarningUtils;
import com.ukefu.webim.web.handler.Handler;
import com.ukefu.webim.web.model.ReqlogWarningAction;
import com.ukefu.webim.web.model.ReqlogWarningContent;
import com.ukefu.webim.web.model.ReqlogWarningMsg;
import com.ukefu.webim.web.model.RequestLog;
import com.ukefu.webim.web.model.SystemConfig;
import com.ukefu.webim.web.model.Template;
import com.ukefu.webim.web.model.User;

/**
 * 系统访问记录
 * @author admin
 *
 */
public class LogIntercreptorHandler implements org.springframework.web.servlet.HandlerInterceptor{
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
	    
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object arg2, ModelAndView arg3) throws Exception {
		HandlerMethod  handlerMethod = (HandlerMethod ) arg2 ;
	    Object hander = handlerMethod.getBean() ;
	    RequestMapping obj = handlerMethod.getMethod().getAnnotation(RequestMapping.class) ;
	    if(!StringUtils.isBlank(request.getRequestURI()) && !(request.getRequestURI().startsWith("/message/ping") || request.getRequestURI().startsWith("/res/css") || request.getRequestURI().startsWith("/error") || request.getRequestURI().startsWith("/im/") || request.getRequestURI().startsWith("/apps/asr/") || request.getRequestURI().startsWith("/apps/robotsmartivr/")  || request.getRequestURI().startsWith("/apps/desktop"))){
	    	RequestLog log = new RequestLog();
	    	User user = (User) request.getSession(true).getAttribute(UKDataContext.USER_SESSION_NAME) ;
	    	if(user == null) {
	    		if(user==null){
	    			String authorization = request.getHeader("authorization") ;
	    			if(StringUtils.isBlank(authorization) && request.getCookies()!=null){
	    				for(Cookie cookie : request.getCookies()){
	    					if(cookie.getName().equals("authorization")){
	    						authorization = cookie.getValue() ; break ;
	    					}
	    				}
	    			}
	    			if(!StringUtils.isBlank(authorization)){
	    				user = (User) CacheHelper.getApiUserCacheBean().getCacheObject(authorization, UKDataContext.SYSTEM_ORGI) ;
	    			}
	    		}
	    	}
			Boolean isSuperUserLogin = (Boolean)request.getSession().getAttribute(UKDataContext.SUPERUSER_LOGIN_SESSION_NAME) ;

			if(isSuperUserLogin != null && isSuperUserLogin){
				log.setField6("superuser");
			}
		    log.setEndtime(new Date()) ;
		    
			if(obj!=null) {
				log.setName(obj.name());
			}
			log.setMethodname(handlerMethod.toString()) ;
			log.setIp(request.getRemoteAddr()) ;
			if(hander!=null) {
				log.setClassname(hander.getClass().toString()) ;
				if(hander instanceof Handler && ((Handler)hander).getStarttime() != 0) {
			    	log.setQuerytime(System.currentTimeMillis() - ((Handler)hander).getStarttime());
			    }
			}
			log.setUrl(request.getRequestURI());
			
			log.setHostname(request.getRemoteHost()) ;
			log.setEndtime(new Date());
			log.setType(UKDataContext.LogTypeEnum.REQUEST.toString()) ;
			log.setReportdic(request.getSession().getId());
			
			if(user!=null){
				
				log.setReportname(user.getClientip());
				
				log.setUserid(user.getId()) ;
				log.setUsername(user.getUsername()) ;
				log.setUsermail(user.getEmail()) ;
				log.setOrgi(user.getOrgi());
			}
			StringBuffer str = new StringBuffer();
			Enumeration<String> names = request.getParameterNames();
			while(names.hasMoreElements()){
				String paraName=(String)names.nextElement();
				if(paraName.indexOf("password") >= 0) {
					str.append(paraName).append("=").append(UKTools.encryption(request.getParameter(paraName))).append(",");
				}else {
					str.append(paraName).append("=").append(request.getParameter(paraName)).append(",");
				}
			}
			
			Menu menu = handlerMethod.getMethod().getAnnotation(Menu.class) ;
			if(menu!=null){
				log.setFuntype(menu.type());
				log.setFundesc(menu.subtype());
				log.setName(menu.name());
			}
			
			log.setParameters(str.toString());
			//预警
			SystemConfig systemConfig = UKTools.getSystemConfig();
			if (systemConfig.isEnablereqlogwarning()) {
				if (!StringUtils.isBlank(systemConfig.getReqlogwarningaction())) {
					List<ReqlogWarningAction> reqlogWarningActionList = systemConfig.getReqlogWarningAction();
					if (reqlogWarningActionList != null && reqlogWarningActionList.size() > 0) {
						List<ReqlogWarningContent> reqlogWarningContentList = new ArrayList<ReqlogWarningContent>();
						StringBuffer trigStr = new StringBuffer();
						//预警内容
						RLogWarningUtils.getWarningContent(reqlogWarningActionList, reqlogWarningContentList, str, trigStr);
						
						log.setTriggerwarnings(trigStr.toString());
						//有预警内容就进行邮件短信发送通知
						if (reqlogWarningContentList != null && reqlogWarningContentList.size() > 0) {
							log.setTriggertime(new Date());
							//预警信息
							ReqlogWarningMsg msg = new ReqlogWarningMsg();
	        				msg.setContent(reqlogWarningContentList);//预警内容
	        				msg.setWarnDate(new Date());
	        				msg.setIp(log.getId());
	        				msg.setUrl(log.getUrl());
	        				msg.setUsername(log.getUsername());
	        				msg.setUserid(log.getUserid());
							//预警对象
	        				List<String> useremailList = new ArrayList<String>();
	        				List<String> usermobileList = new ArrayList<String>();
	        				RLogWarningUtils.getTouser(systemConfig.getReqlogwarningtouser(), useremailList, usermobileList);
	        				
							//邮件
							if (!StringUtils.isBlank(systemConfig.getReqlogwarningemailid()) && !StringUtils.isBlank(systemConfig.getReqlogwarningemailtp()) && useremailList.size() > 0) {
		        				Template template = UKTools.getTemplate(systemConfig.getReqlogwarningemailtp()) ;
		    					if (template!=null) {
		    						Map<String, Object> values = new HashMap<String, Object>();
		    						values.put("msg", msg) ;
//		    						String content = UKTools.getTemplet(template.getTemplettext(), values) ;
//		    						System.out.println("邮件预警");
//		    						UKTools.sendMassMail(useremailList, "请求预警信息", content, systemConfig.getReqlogwarningemailid(), UKDataContext.SYSTEM_ORGI);
		    					}
		        			}
		        			//短信
		        			if (!StringUtils.isBlank(systemConfig.getReqlogwarningsmsid()) && !StringUtils.isBlank(systemConfig.getReqlogwarningsmstp())&& usermobileList.size() > 0) {
		        				Template template = UKTools.getTemplate(systemConfig.getReqlogwarningsmstp()) ;
		    					if (template!=null) {
		    						Map<String, Object> values = new HashMap<String, Object>();
		    						values.put("msg", msg) ;
		    					}
		        			}
						}
					}
				}
			}
			
			UKTools.published(log);
	    }
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object arg2) throws Exception {
		HandlerMethod  handlerMethod = (HandlerMethod ) arg2 ;
	    Object hander = handlerMethod.getBean() ;
	    if(hander instanceof Handler) {
	    	((Handler)hander).setStarttime(System.currentTimeMillis());
	    }
		return true;
	}
	
}
